package com.prj.ufdm.core.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map.Entry;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * Description: MultipartFile 上传工具
 * @author   
 * @date 2019年10月16日
 */
public class UfdmRequestHttpUtilMultipartFile 
{
	private static Logger log = LoggerFactory.getLogger(UfdmRequestHttpUtilMultipartFile.class);
	
	private final static String BOUNDARY = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");// 边界标识
	private final static String PREFIX = "--";// 必须存在
	private final static String LINE_END = "\r\n";
	
	public static void main(String[] args) throws Exception {
		
		String reqUrl = "http://115.233.221.131:27401/api/file/upload";
		Map<String,String> reqHeadMap = new HashMap<String,String>();
		reqHeadMap.put("Auth-User-Token", "88B7F80A99904B8B9548AF0A6A056AF4");
		Map<String,String> reqParamMap = new HashMap<String,String>();
		reqParamMap.put("aliases", "测试的图片");
		Map<String, MultipartFile> reqFileMap = new HashMap<String, MultipartFile>();
        
        // 通过文件路径读取
		String filePath = "D:\\newdown\\QQ截图20191218190710.png";
		reqFileMap.put("file", getMulFileByPath(filePath));
		
		// 通过流文件读取
		/**
        String file2Path = "D:\\newdown\\2.jpg";
        File file = new File(file2Path);
        FileInputStream fis = new FileInputStream(file);
		reqFileMap.put("file", getMulFileByStream("2.jpg",fis));
		*/
		
		String encode = "utf-8";
		System.out.println(postMultipartFile(reqUrl,reqHeadMap,reqParamMap,reqFileMap,encode));
	}
	
	/**
	 * Description: FileInputStream 转为 MultipartFile 
	 * @param fileName
	 * @param fileInputStream
	 * @return
	 * @throws Exception
	 * @author 
	 * @date 2019年10月16日
	 * @version 1.0
	 */
	public static MultipartFile getMulFileByStream(String fileName,FileInputStream fileInputStream) throws Exception {
		FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem fileItem = factory.createItem(fileName, MediaType.APPLICATION_OCTET_STREAM_VALUE, false,fileName);  
        IOUtils.copy(fileInputStream, fileItem.getOutputStream());
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    } 
	
	/**
	 * Description: 通过文件路径 filePath 获取 MultipartFile 文件
	 * @param filePath
	 * @return
	 * @throws Exception
	 * @author 
	 * @date 2019年10月16日
	 * @version 1.0
	 */
	public static MultipartFile getMulFileByPath(String filePath) throws Exception {
		FileItemFactory factory = new DiskFileItemFactory(16, null);
        File file = new File(filePath);
        FileItem fileItem = factory.createItem(file.getName(), MediaType.APPLICATION_OCTET_STREAM_VALUE, false,file.getName());  
        IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    } 
	

	/**
	 * Description: 通过文件路径 filePath 获取 MultipartFile 文件
	 * @param requestUrl
	 * @param reqHeadMap
	 * @param reqHeadMap
	 * @return
	 * @throws Exception
	 * @author 
	 * @date 2019年10月16日
	 * @version 1.0
	 */
	public static String postMultipartFile(String requestUrl,Map<String,String> reqHeadMap,Map<String, String> reqParam, Map<String, MultipartFile> requestFile,String encode) throws Exception{
		HttpURLConnection conn = null;
		InputStream input = null;
		OutputStream os = null;
		BufferedReader br = null;
		StringBuffer buffer = null;
		try {
			URL url = new URL(requestUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(1000 * 10);
			conn.setReadTimeout(1000 * 10);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Accept", "*/*");
			conn.setRequestProperty("Connection", "keep-alive");
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			// 请求参数部分
			writeHeader(conn,reqHeadMap,encode);
			conn.connect();
 
			// 往服务器端写内容 也就是发起http请求需要带的参数
			os = new DataOutputStream(conn.getOutputStream());
			// 请求参数部分
			writeParams(reqParam, os);
			// 请求上传文件部分
			writeFile(requestFile, os);
			// 请求结束标志
			String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
			os.write(endTarget.getBytes());
			os.flush();
			
			// 读取服务器端返回的内容
			System.out.println("======================响应体=========================");
			System.out.println("ResponseCode:" + conn.getResponseCode()	+ ",ResponseMessage:" + conn.getResponseMessage());
			if(conn.getResponseCode()==200){
				input = conn.getInputStream();
			}else{
				input = conn.getErrorStream();
			}
			
			br = new BufferedReader(new InputStreamReader(input, "UTF-8"));		
			buffer = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				buffer.append(line);
			}
			//......
			System.out.println("返回报文:" + buffer.toString());
 
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new Exception(e);
		} finally {
			try {
				if (conn != null) {
					conn.disconnect();
					conn = null;
				}
 
				if (os != null) {
					os.close();
					os = null;
				}
 
				if (br != null) {
					br.close();
					br = null;
				}
			} catch (IOException ex) {
				log.error(ex.getMessage(), ex);
				throw new Exception(ex);
			}
		}
		return buffer.toString();
	}
 
	/**
	 * 参数写入
	 * @throws Exception 
	 * @throws IOException
	 */
	private static void writeParams(Map<String, String> reqParam,OutputStream os) throws Exception {
		if (reqParam != null && !reqParam.isEmpty()) {
			StringBuilder requestParams = new StringBuilder();
			Set<Map.Entry<String, String>> set = reqParam.entrySet();
			Iterator<Entry<String, String>> it = set.iterator();
			while (it.hasNext()) {
				Entry<String, String> entry = it.next();
				requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
				requestParams.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"").append(LINE_END);
				requestParams.append("Content-Type: text/plain; charset=utf-8").append(LINE_END);
				requestParams.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
				requestParams.append(LINE_END);  // 参数头设置完以后需要两个换行，然后才是参数内容
				requestParams.append(entry.getValue());
				requestParams.append(LINE_END);
			}
			os.write(requestParams.toString().getBytes());
			os.flush();
		}
	}
 
	/**
	 * 头信息写入
	 * @throws Exception 
	 * @throws IOException
	 * 
	 */
	private static void writeHeader(HttpURLConnection urlCon,Map<String, String> reqHeadMap,String encode) throws Exception {
		if(reqHeadMap!=null) {
			String tempKey;
			String tempValue;
			Set<String> headKey = reqHeadMap.keySet();
			Iterator<String> it = headKey.iterator();
			while(it.hasNext()){
				tempKey = it.next();
				tempValue = reqHeadMap.get(tempKey)!=null ? URLEncoder.encode(reqHeadMap.get(tempKey),encode) : "";
				urlCon.setRequestProperty(tempKey, tempValue);
			}
		}
	}
	
	/**
	 * 文件写入
	 * 
	 */
	private static void writeFile(Map<String, MultipartFile> requestFile,OutputStream os) throws Exception {
		InputStream is = null;
		try{
			if (requestFile != null && !requestFile.isEmpty()) 
			{
				Set<Map.Entry<String, MultipartFile>> set = requestFile.entrySet();
				Iterator<Entry<String, MultipartFile>> it = set.iterator();
				while (it.hasNext()) {
					StringBuilder requestParams = new StringBuilder();
					Entry<String, MultipartFile> entry = it.next();
					if(entry.getValue() == null){//剔除value为空的键值对
						continue;
					}
					requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
					requestParams.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"; filename=\"")
							.append(entry.getValue().getName()).append("\"").append(LINE_END);
					requestParams.append("Content-Type:").append(entry.getValue().getContentType()).append(LINE_END);
					requestParams.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
					requestParams.append(LINE_END);
 
					os.write(requestParams.toString().getBytes());
					os.write(entry.getValue().getBytes());
					os.write(LINE_END.getBytes());
					os.flush();
				}
			}
		}catch(Exception e){
			log.error("writeFile failed", e);
			throw new Exception(e);
		}finally{
			try{
				if(is!=null){
					is.close();
				}
			}catch(Exception e){
				log.error("writeFile FileInputStream close failed", e);
				throw new Exception(e);
			}
		}
	}
 
	/**
	 * ContentType(这部分可忽略，MultipartFile有对应的方法获取)
	 * @Description:
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static String getContentType(MultipartFile file) throws Exception{
		String streamContentType = "application/octet-stream";
		String imageContentType = "";
		ImageInputStream image = null;
		try {
			image = ImageIO.createImageInputStream(file);
			if (image == null) {
				return streamContentType;
			}
			Iterator<ImageReader> it = ImageIO.getImageReaders(image);
			if (it.hasNext()) {
				imageContentType = "image/" + it.next().getFormatName();
				return imageContentType;
			}
		} catch (IOException e) {
			log.error("method getContentType failed", e);
			throw new Exception(e);
		} finally {
			try{
				if (image != null) {
					image.close();
				}
			}catch(IOException e){
				log.error("ImageInputStream close failed", e);;
				throw new Exception(e);
			}
			
		}
		return streamContentType;
	}
	

	
}
